package com.itheima.geteayapp.filters;

import com.itheima.common.constants.SystemConstants;
import com.itheima.common.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AppUserAuthorizeFilter implements GlobalFilter, Ordered {
    /**
     * 统一鉴权
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //0.获取请求与响应
        ServerHttpRequest req = exchange.getRequest();
        ServerHttpResponse res = exchange.getResponse();
        //获取请求路劲
        String path = req.getURI().getPath();
        //如果是登录请求地址则放行
        if (path.endsWith("/login_auth/")){
            return chain.filter(exchange);
        }
        //1.从请求头中获取token
        String token = req.getHeaders().getFirst("token");
        //2.有值，验证有效期
        if (!StringUtils.isEmpty(token)){
            int verifyToken = AppJwtUtil.verifyToken(token);

            if (SystemConstants.JWT_OK==verifyToken){
                //获取载荷
                Claims claimsBody = AppJwtUtil.getClaimsBody(token);
                //取出载荷中创建token时的id
                Integer id = (Integer) claimsBody.get("id");
                req.mutate().header(SystemConstants.USER_HEADER_NAME,id.toString());
                return chain.filter(exchange);
            }
        }
        res.setStatusCode(HttpStatus.UNAUTHORIZED);
        return res.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
